package cn.yanghan.service.impl;

import cn.yanghan.domain.LoginUser;
import cn.yanghan.domain.TKillOrder;
import cn.yanghan.domain.TKillOrderItem;
import cn.yanghan.dto.KillOrderDto;
import cn.yanghan.dto.OrderSaveDto;
import cn.yanghan.mapper.TKillOrderMapper;
import cn.yanghan.service.ITKillOrderItemService;
import cn.yanghan.service.ITKillOrderService;
import cn.yanghan.utils.exception.Assert;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yh
 * @since 2022-04-23
 */
@Service
public class TKillOrderServiceImpl extends ServiceImpl<TKillOrderMapper, TKillOrder> implements ITKillOrderService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ITKillOrderItemService itemService;
    /**
     * 保存订单
     * @param dto
     * @return
     */
    @Override
    @Transactional
    public String saveOrder(OrderSaveDto dto) {

        //1。参数判断
        //2.条件判断，必须登录
        LoginUser login = new LoginUser();
        login.setId(3L);
        Assert.assertNotNull(login,"请登录");

        //3.根据单号获取欲创订单-redis
        //3.1 key:使用用户id和订单号进行拼接，获取欲创订单
        String key = "killorder:"+dto.getOrderNo()+":"+login.getId();
        //4.拿到欲创订单
        KillOrderDto killOrderDto  = (KillOrderDto) redisTemplate.opsForValue().get(key);
        Assert.assertNotNull(killOrderDto,"秒杀不存在，或者超时");
        //4.1构建订单数据（订单-明细）
        TKillOrder killOrder = new TKillOrder();
        killOrder.setCreateTime(new Date());
        killOrder.setKillCount(1);
        killOrder.setOrderNo(dto.getOrderNo());
        killOrder.setTotalPrice(killOrderDto.getPrice());
        //未支付
        killOrder.setStatusOrder(killOrder.ORDER_STATUS_UNPAY);
        insert(killOrder);

        //保存到数据库
        TKillOrderItem item = new TKillOrderItem();
        item.setCreateTime(killOrder.getCreateTime());
        item.setCount(1);
        item.setCourseId(killOrderDto.getCourseId());
        item.setCourseName(killOrderDto.getCourseName());
        item.setKillId(killOrderDto.getKillId());
        item.setKillOrderId(killOrder.getId());
        item.setPrice(killOrderDto.getPrice());
        itemService.insert(item);

        redisTemplate.delete(key);
        return dto.getOrderNo();
    }
}
